package com.jianganming.interpreter;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class GPCalculator {
    private Stack<IArithmeticInterpreter> stack = new Stack<>();

    private List<String> symbols = new ArrayList<>();

    public GPCalculator(String expression) {
        this.parseOne(expression);
    }

    private void parseOne(String expression) {
        String [] elements = expression.split(" ");
        IArithmeticInterpreter leftExpr, rightExpr;
        for (int i = 0; i < elements.length; i++) {
            String operator = elements[i];
            if (OperatorUtil.isOneOperator(operator)){
                leftExpr = this.stack.pop();
                rightExpr = new NumInterpreter(elements[++i]);
                int result = OperatorUtil.getInterpreter(leftExpr, rightExpr, operator).interpret();
                this.stack.push(new NumInterpreter(result+""));
            }else if(OperatorUtil.isTwoOperator(operator)){
                symbols.add(operator);
            }else{
                NumInterpreter numInterpreter = new NumInterpreter(elements[i]);
                this.stack.push(numInterpreter);
            }

        }
    }

    private void parseTwo(String expression) {
        String [] elements = expression.split(" ");
        IArithmeticInterpreter leftExpr, rightExpr;
        for (int i = 0; i < elements.length; i++) {
            String operator = elements[i];
            if (OperatorUtil.isTwoOperator(operator)){
                leftExpr = this.stack.pop();
                rightExpr = new NumInterpreter(elements[++i]);
                this.stack.push(OperatorUtil.getInterpreter(leftExpr, rightExpr,operator));
            }
            else{
                NumInterpreter numInterpreter = new NumInterpreter(elements[i]);
                this.stack.push(numInterpreter);
            }

        }
    }

    public int calculate() {
        String expression = "";
        for (int i = 0; i < stack.size(); i++) {
            expression = expression+stack.get(i).interpret()+" ";
            for (int j = i; j < symbols.size(); j++) {
                expression+= symbols.get(j)+" ";
                break;
            }
        }
        stack.clear();
        symbols.clear();
        System.out.println(expression);
        parseTwo(expression.trim());

        return this.stack.pop().interpret();
    }

}
